import { Directive, DirectiveBinding } from "vue";
import { includes } from '../../../../../sharehouse/vue-storefront/packages/middleware/src/helpers/utils';
import { hasClass } from '../../../../vue3-element-admin/src/utils/index';

export const labelFly: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    /**
     * 基础组件-左侧标签-label悬浮效果
     * 设置：placeholder = ''，否则会导致文字重复
     * 目前不直接支持的组件
     * el-date-picker、el-time-picker、el-cascader
     * 兼容示例：外层包一层span
     * <span v-label-fly="'日期选择'">
            <el-date-picker type="date" placeholder="" v-model="form.date"></el-date-picker>
        </span>
     */
    const label = document.createElement('span');
    label.textContent = binding.value;
    label.classList.add('label-fly-wrapper');
    el.prepend(label);

    label.classList.add('label-fly');

    // 监听 focus 和 blur 事件
    const inputElement = el.querySelector('input,textarea') as HTMLInputElement | null;
    if (inputElement) {
        let selectHasValue = inputElement?.className.includes('el-select__input') && inputElement?.parentElement?.parentElement?.childElementCount === 1;
        if (!!inputElement.value || selectHasValue) {
            label.classList.add('is-focused');
         }else{
            label.classList.remove('is-focused');
         }
        if(inputElement?.previousElementSibling?.className){
            if(inputElement?.previousElementSibling?.className.includes("el-input__prefix") || inputElement?.className.includes('el-range-input')){
                label.classList.add('label-fly-prefix')
            }
        }
        inputElement.addEventListener('focus', () => {
            label.classList.add('is-focused');
        });
        inputElement.addEventListener('input', () => {
            if (!!inputElement.value) {
               label.classList.add('is-focused');
            }
        });
        inputElement.addEventListener('blur,change', () => {
            if (!!inputElement.value) {
               label.classList.add('is-focused');
            }else{
                label.classList.remove('is-focused');
            }
        });
        inputElement.addEventListener('clear', () => {
            label.classList.remove('is-focused');
        });
    }
    
  },
  unmounted(el) {
    const label = el.querySelector('.label-fly-wrapper');
    if (label) {
      label.remove();
    }
  }
};